package com.cws.listener;


import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.lang3.StringUtils;

import com.cws.web.UserSession;


public class CommonSessionListener implements HttpSessionAttributeListener,HttpSessionListener {

	/** 保存已登录的用户信息的 Map，key 为登录名， value 为其对应的 session 对象 */
	private Map<String, HttpSession> loginedUsers = new ConcurrentHashMap<String, HttpSession>();
	
	@Override
	public void sessionCreated(HttpSessionEvent se) {
		// TODO Auto-generated method stub

	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		
		if(loginedUsers.containsValue(se.getSession())){
			HttpSession session;
			for(String key : loginedUsers.keySet()){
				session = loginedUsers.get(key);
				if(session == se.getSession()){
					loginedUsers.remove(key);
					return;
				}
			}
		}
	}

	@Override
	public void attributeAdded(HttpSessionBindingEvent se) {
		if (UserSession.USER_SESSION_KEY.equals(se.getName())) {
			userLoginIdBinding2HttpSession(se.getSession(),(UserSession)se.getValue() );
		}
		

	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent se) {
		// TODO Auto-generated method stub

	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent se) {
		// TODO Auto-generated method stub

	}

	
	private void userLoginIdBinding2HttpSession(HttpSession session, UserSession userSession) {
		if (null == userSession || StringUtils.isEmpty(userSession.getLoginId())) {
			return;
		}

        synchronized (loginedUsers) {
            if (loginedUsers.containsKey(userSession.getLoginId())) {
                HttpSession oldSession = loginedUsers.remove(userSession.getLoginId());
                if (null != oldSession && oldSession != session) {
                    oldSession.invalidate(); // 注销掉以前的session
                    loginedUsers.put(userSession.getLoginId(), session); // 绑定新的session
                }
            }else{
            	loginedUsers.put(userSession.getLoginId(), session); // 绑定新的session
            }
        }
	}
	
	
	
	
	
	
	
	
	
}
